package cn.aifeix.lxyc.exception;

import cn.aifeix.lxyc.enums.GlobalErrorCodeEnum;
import cn.aifeix.lxyc.result.JSONResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        return JSONResult.error(GlobalErrorCodeEnum.ERROR);
    }

    @ExceptionHandler(GlobalException.class)
    public JSONResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return JSONResult.error(e);
    }

    /**
     * 自定义参数校验的全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error ->{
            sb.append("--" + error.getDefaultMessage() + "--");
        });
        return JSONResult.error(sb.toString(),GlobalErrorCodeEnum.COMMON_PARAM_JSR303_ERROR.getCode());
    }
}
